<?php


namespace app\common\service;


use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use think\Exception;

/**
 * @Author zengxin(573908667@qq.com)
 * Class Email
 * @package app\common\service
 */
class Email
{
    protected $mail;
    protected $error;

    public function __construct()
    {
        $this->mail            = new PHPMailer(true);
        $this->mail->CharSet   = 'UTF-8';
        $this->mail->SMTPDebug = SMTP::DEBUG_OFF;                      //Enable verbose debug output
        $this->mail->isSMTP();                                            //Send using SMTP
        $this->mail->Host       = app()->env->get('email_host');                     //Set the SMTP server to send through
        $this->mail->SMTPAuth   = true;                                   //Enable SMTP authentication
        $this->mail->Username   = app()->env->get('email_username');                   //SMTP username
        $this->mail->Password   = app()->env->get('email_password');                               //SMTP password
        $this->mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         //Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
        $this->mail->Port       = 465;                                    //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
        $this->mail->setFrom(app()->env->get('email_from'));
    }

    /**
     * 发送邮件
     * @Author zengxin(573908667@qq.com)
     * @param $email
     * @param $title
     * @param $body
     * @param string $file
     * @return bool
     * @throws \PHPMailer\PHPMailer\Exception
     */
    public function send($email, $title, $body, $file = '')
    {
        try {
            //Recipients
            $this->mail->addAddress($email);

            //Attachments
            if(!empty($file)) {
                $this->mail->addAttachment($file);    //Optional name  附件资料
            }

            //Content
            $this->mail->isHTML(true);                                  //Set email format to HTML
            $this->mail->Subject = $title;
            $this->mail->Body    = $body;
            $this->mail->AltBody = '';

            $this->mail->send();
            return true;
        } catch (Exception $e) {
            $this->error = $this->mail->ErrorInfo;
            return false;
        }
    }

    public function getError()
    {
        return $this->error;
    }
}